import { RoutesType, SiderbarRoutesType } from "@/types/meuns.type";
import { create } from "zustand";
import { defaultRoutes } from "@/routers";
// routes: [],
//     addRoutes: [],
//     defaultRoutes: [],
//     topbarRouters: [],
//     sidebarRouters: []

type State = {
  defaultRoutes: RoutesType;
  sidebarRoutes: SiderbarRoutesType;
};

type Actions = {
  initRouter: () => void;
  setSidebarRoutes: () => void;
};

function getSidebarRoutes(defaultRoutes: RoutesType): SiderbarRoutesType {
  let reserveRoutes: SiderbarRoutesType = [];

  const routes = defaultRoutes.filter((route) => !route.hidden);

  reserveRoutes = routes.map((route) => {
    // 需要外层框架但是没有子菜单这种情况，比如：Home
    // if (route.affix && route.children) {
    //   const child = route?.children[0];
    //   return {
    //     name: child.name,
    //     key: child.path,
    //     path: child.path,
    //     icon: child.meta?.icon,
    //     title: child.meta?.title || child.name,
    //   };
    // }
    // 通常情况
    return {
      name: route.name,
      key: route.path,
      path: route.path,
      icon: route.meta?.icon,
      title: route.meta?.title || route.name,
      children: route.children ? getSidebarRoutes(route.children) : undefined,
    };
  });

  return reserveRoutes;
}

const useMenusStore = create<State & Actions>((set) => ({
  defaultRoutes: defaultRoutes,
  sidebarRoutes: [],
  initRouter: () =>
    set(() => ({ defaultRoutes: defaultRoutes, sidebarRouters: [] })),
  setSidebarRoutes: () => {
    fetch("/data/menus.json")
      .then((res) => {
        return res.json();
      })
      .then((data) => {
        const sidebarRoutes = [
          ...getSidebarRoutes(defaultRoutes),
          ...getSidebarRoutes(data),
        ];
        set((state) => ({
          ...state,
          sidebarRoutes,
        }));
      });
  },

  // increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
  // removeAllBears: () => set({ bears: 0 }),
  // updateBears: (newBears) => set({ bears: newBears }),
}));

export default useMenusStore;
